import os
from enum import Enum, unique
import json
from utils.core.docker_core.container_properties import ContainerProperties  
from utils.core.docker_core.image_properties import ImageProperties

@unique
class ContainerState(Enum):
    NO_EXIST = -1
    STOP = 0
    RUNNING = 1

    def get_state(self, status):
        """将容器状态转化为枚举"""
        if status == 'running':
            return ContainerState.RUNNING.value
        elif status == 'exited':
            return ContainerState.STOP.value
        else:
            return ContainerState.NO_EXIST.value


def get_container_state(container_name=str):
    """获取容器状态,返回值为 ContainerState 的枚举结果

    `return`:
        -1 不存在该容器;  0 容器在运行; 1 容器已经停止
    """
    container_state = ContainerProperties(container_name).status
    if container_state == 'running':
        return ContainerState.RUNNING.value
    elif container_state == 'exited':
        return ContainerState.STOP.value
    else:
        return ContainerState.NO_EXIST.value

def get_images_id_by_container_name(container_name=str):
    """根据容器名 获取镜像 id"""
    container_info = ContainerProperties(container_name)
    if container_info:
        return ImageProperties(container_info.image_id)
    return None

def stop_container(container_name=str):
    """关闭容器"""
    os.popen("docker stop {}".format(container_name))

def remove_container(container_name=str, isForce=False):
    """删除容器(默认不强制删除)"""
    command = "docekr rm "
    if isForce: 
        command += " -f "
    command += container_name
    os.popen(command)